package com.zhizhi.util;

import cn.hutool.core.util.ObjectUtil;
import com.zhizhi.common.constant.SystemConstant;
import com.zhizhi.domain.RequestTokenBO;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *  请求token工具类
 */
public class RequestTokenUtil {

    private static ThreadLocal<RequestTokenBO> requestTokenBOThreadLocal = new ThreadLocal<>();

    public static void setAccount(HttpServletRequest request, RequestTokenBO requestTokenBO) {
        request.setAttribute(SystemConstant.KEY_ACCOUNT, requestTokenBO);
        requestTokenBOThreadLocal.set(requestTokenBO);
    }

    public static RequestTokenBO getThreadLocalAccount() {
        return requestTokenBOThreadLocal.get();
    }

    public static RequestTokenBO getRequestAccount() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNotNull(requestAttributes)) {
            HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
            if (ObjectUtil.isNotNull(request)) {
                return (RequestTokenBO) request.getAttribute(SystemConstant.KEY_ACCOUNT);
            }
        }
        return null;
    }
}